<!--系统文件-->
<template>
  <div id="documentExplorer" class="app-container flex-row">
    <div class="conmmon-container-left" style="width:200px;border-right: 1px solid #E6E6E6;">

      <el-tree
        v-loading="treeLoading"
        class="common-el-tree scrollbar-no-width"
        node-key="id"
        :default-expanded-keys="expandedKeys"
        :props="fileCatalogProps"
        :load="loadFileCatalog"
        lazy
        @node-click="handleCatalogNodeClick">
        <div slot-scope="{ node,data }" class="custom-tree-node">
          <file-catalog-svg-icon :type="data.catalogType" />
          <span class="text">{{ node.label }}</span>
        </div>
      </el-tree>
    </div>
    <div class="conmmon-container-main flex-main">
      <systemDocument ref="systemDocument" :catalog-id="catalogId" :file-path="fileFullPath" @handleEvent="handleEvent" @callbackCatalog="callbackCatalog" />
    </div>
    <!--新建文件夹-->
    <model-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      @close="dialogVisible=!dialogVisible">
      <el-form ref="dataForm" :rules="fileCatalogRule" :model="fileCatalogConfigRecord" label-position="right" label-width="100px">
        <el-form-item label="文件夹路径">
          <el-breadcrumb separator-class="el-icon-arrow-right" style="    line-height: 27px;">
            <el-breadcrumb-item v-for="(item,index) in fileFullPath" :key="item.index">
              <el-link v-if="index != fileFullPath.length-1" :underline="false">
                {{ item.catalogName }}
              </el-link>
              <el-link v-if="index == fileFullPath.length-1" :underline="false" style="color: rgb(71, 119, 231) !important;">
                {{ item.catalogName }}
              </el-link>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </el-form-item>
        <el-form-item label="文件夹名称" prop="catalogName">
          <el-input v-model="fileCatalogConfigRecord.catalogName" maxlength="10" show-word-limit placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="文件夹路径" prop="catalogPath">
          <el-input v-model="fileCatalogConfigRecord.catalogPath" maxlength="20" show-word-limit placeholder="请输入文件夹路径" />
        </el-form-item>
        <el-form-item label="是否允许删除" prop="isAllowDeleted">
          <el-radio v-model="fileCatalogConfigRecord.isAllowDeleted" label="0">不允许</el-radio>
          <el-radio v-model="fileCatalogConfigRecord.isAllowDeleted" label="1">允许</el-radio>
        </el-form-item>
      </el-form>
      <template slot="footer">
        <el-button type="primary" @click="newFolder()">确定</el-button>
      </template>
    </model-dialog>
  </div>
</template>

<script>
import systemDocument from './systemDocument'

export default {
  components: { systemDocument },
  data() {
    return {
      treeLoading: false,
      fileCatalogProps: {
        label: 'catalogName',
        children: 'catalogs',
        isLeaf: 'leaf'
      },
      treeDataMap: new Map(),
      expandedKeys: [],
      catalogId: '',
      selectedNode: {},
      fileFullPath: [],
      fileCatalogConfigRecord: {},
      fileCatalogRule: {
        catalogName: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        catalogPath: [
          { required: true, message: '请输入路径', trigger: 'blur' },
          { validator: this.$validate.validateEngOrNum, trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      dialogTitle: '新建文件夹',
      reNameVisible: false

    }
  },
  mouted() {},
  watch: {

  },
  created() {
  },
  methods: {
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        }).catch(_ => {})
    },
    async loadFileCatalog(node, resolve) {
      this.selectedNode = node
      try {
        this.treeLoading = true
        if (node.level === 0) {
          const catalogResponse = await this.$store.dispatch('listFileSystemCatalog')
          if (catalogResponse.length === 0) {
            this.initDocsCatalog()
          } else {
            catalogResponse.forEach(element => {
              if (!this.treeDataMap.has(element.id)) {
                this.treeDataMap.set(element.id, element)
              }
            })
            var temp = catalogResponse[0]
            this.expandedKeys.push(temp.id)

            this.getFullPath(temp.id)
            this.$nextTick(() => {
              this.catalogId = temp.id
            })
          }
          //
          resolve(catalogResponse)
        } else {
          const catalogResponse = await this.$store.dispatch('listFileCatalogByPid', { pid: node.data.id })
          catalogResponse.forEach(element => {
            if (!this.treeDataMap.has(element.id)) {
              this.treeDataMap.set(element.id, element)
            }
          })
          resolve(catalogResponse)
        }
        this.treeLoading = false
      } catch (err) {
        console.log(err)
      }
    },
    // 获取完整路径
    getFullPath(id) {
      var datas = []
      this.treeDataMap.forEach(item => {
        datas.push(item)
      })
      var ids = this.T.getParentPid(datas, '0', id, 'catalogPid', 'id').reverse()
      ids.push(id)
      this.fileFullPath = []
      datas.forEach(item => {
        if (ids.includes(item.id)) {
          this.fileFullPath.push({ id: item.id, catalogName: item.catalogName })
        }
      })
    },
    initDocsCatalog() {
      this.$alert('您还初始化文件目录,请先进行初始化', '警告', {
        showClose: false,
        confirmButtonText: '初始化',
        callback: action => {
          this.$store.dispatch('initDocsCatalog', {}).then((res) => {
            this.$modal.msgSuccess('初始化成功')
            window.location.reload()
          }).catch((_) => {})
        }
      })
    },
    handleCatalogNodeClick(data, node) {
      console.log(node)

      this.getFullPath(data.id)
      this.$nextTick(() => {
        this.catalogId = data.id
        this.selectedNode = node
      })
    },

    handleEvent(e) {
      if (!this.catalogId) {
        this.$modal.msgWarning('此文件夹不允许操作!')
        return
      }
      if (e === 'newFolder') {
        this.handleCreateFolder()
      }
      if (e === 'removeFolder') {
        this.handleRemoveFolder()
      }
    },
    callbackCatalog(catalogId) {
      this.catalogId = catalogId
      this.expandedKeys.push(catalogId)
      this.getFullPath(catalogId)
    },
    /* 新增*/
    handleCreateFolder() {
      console.log(this.selectedNode)
      this.fileCatalogConfigRecord = {
        catalogPid: this.catalogId,
        isEncryption: '0',
        isAllowNewFile: '1',
        isAllowNewFolder: '1',
        isAllowRead: '0',
        isAllowDeleted: '0'
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    newFolder() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$store.dispatch('saveFileCatalog', this.fileCatalogConfigRecord).then(response => {
            this.dialogVisible = false
            this.$modal.msgSuccess('添加成功')
            this.refreshTreeNode(this.selectedNode, this.catalogId)
            this.$refs.systemDocument.handleReset()
          }).catch(() => {
          })
        }
      })
    },
    handleRemoveFolder() {
      var data = this.selectedNode.data
      if (!data) {
        this.$modal.msgWarning('请选择文件夹')
        return
      }
      if (data.isBuiltIn === 1) {
        this.$modal.msgWarning('内置文件夹无法删除')
        return
      }
      if (data.isEncryption === '1') {
        this.$modal.msgWarning('加密文件夹无法删除')
        return
      }
      if (data.isAllowDeleted === '0') {
        this.$modal.msgWarning('此文件夹不允许删除')
        return
      }
      this.$confirm(`此操作将永久删除文件夹[${data.catalogName}], 是否继续?`, '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('removeFileCatalog', { id: data.id }).then(response => {
          this.$modal.msgSuccess('操作成功')
          if (this.selectedNode.parent) {
            this.refreshTreeNode(this.selectedNode.parent, this.selectedNode.parent.data.id)
          }
        }).catch(() => {})
      }).catch(() => {})
    },
    async refreshTreeNode(node, catalogId) {
      console.log(node)
      node.childNodes = []
      const catalogResponse = await this.$store.dispatch('listFileCatalogByPid', { pid: catalogId })
      node.doCreateChildren(catalogResponse)

      catalogResponse.forEach(element => {
        if (!this.treeDataMap.has(element.id)) {
          this.treeDataMap.set(element.id, element)
        }
      })
    }

  }
}
</script>

<style lang="scss" >
  #documentExplorer{
    .common-el-tree{
      .text{
        font-size: 12px;
      }
      .el-tree-node__content {
        height: 36px;
        line-height: 36px;
      }
    }
  }
</style>
